package com.grape.ciq.api.redbook.internal.parse;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public abstract class WebUtils {
	private static final Log logger = LogFactory.getLog(WebUtils.class);

	/**
	 * 发起https请求并获取结果
	 * 
	 * @param requestUrl
	 *            请求地址
	 * @param requestMethod
	 *            请求方式（GET、POST、PUT）
	 * @param outputStr
	 *            提交的数据
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
	 */

	public static String httpsRequest(String requestUrl, String outputData,
			String requestMethod, String sign, String appKey) {
		StringBuilder sb = new StringBuilder();
		String time = System.currentTimeMillis() / 1000 + "";
		try {
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL url = new URL(requestUrl);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
			/*
			 * 小红书 系统参数指和具体的业务无关，但是每次接口调用都需要的输入参数，系统参数通过HTTP请求的header传入，系统参数如下：
			 * timestamp 接口调用时的时间戳，即当前时间戳（时间戳：当前距离Epoch（1970年1月1日)
			 * 以秒计算的时间，即unix-timestamp，请使用精确到秒的时间戳。 app-key 三方商家在ark系统的唯一标示 sign
			 * 参数的签名结果
			 */
			httpUrlConn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
			httpUrlConn.setRequestProperty("app-key", appKey);
			httpUrlConn.setRequestProperty("sign", sign);
			httpUrlConn.setRequestProperty("timestamp", time);
			httpUrlConn.setSSLSocketFactory(ssf);

			httpUrlConn.setDoOutput(true);  // 禁止 URL 连接进行输出，默认为“false”   
			httpUrlConn.setDoInput(true);    // 使用 URL 连接进行输入，默认为“true”   
			httpUrlConn.setUseCaches(false); // 忽略缓存 

			httpUrlConn.setRequestMethod(requestMethod);
			if (requestMethod.equals("GET")) {
				httpUrlConn.connect();
			}
			
			//POST 参数部分需要以“字符流”的形式处理
			if ((requestMethod.equals("POST") || requestMethod.equals("PUT"))
					&& outputData != null && !"".equals(outputData)) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				outputStream.write(outputData.getBytes("utf-8"));
				outputStream.close();
			}
			//发送数据的是下面的inputStreamReader
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

			String partResult;
			while ((partResult = bufferedReader.readLine()) != null) {
				sb.append(partResult);
			}

			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			httpUrlConn.disconnect();
		} catch (Exception e) {
			logger.warn("网络请求出错", e);
		}
		return sb.toString();
	}

	/**
	 * 发起http请求并获取结果
	 * 
	 * @param requestUrl
	 *            请求地址
	 * @param requestMethod
	 *            请求方式（GET、POST）
	 * @param outputStr
	 *            提交的数据
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
	 */
	public static String httpRequest(String requestUrl, String outputData,
			String requestMethod, String sign, String appKey) {
		URL u = null;
		HttpURLConnection con = null;
		StringBuffer buffer = new StringBuffer();

		// 尝试发送请求
		try {
			u = new URL(requestUrl);
			con = (HttpURLConnection) u.openConnection();
			con.setRequestMethod(requestMethod);
			con.setDoOutput(true);
			con.setDoInput(true);
			con.setUseCaches(false);
			con.setRequestProperty("Content-Type","application/json;charset=utf-8");
			con.setRequestProperty("app-key", appKey);
			con.setRequestProperty("sign", sign);
			con.setRequestProperty("timestamp", System.currentTimeMillis()/ 1000 + "");
			OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "utf-8");
			if ((requestMethod.equals("POST") || requestMethod.equals("PUT"))
					&& outputData != null && !"".equals(outputData)) {
				osw.write(outputData);
			}
			osw.flush();
			osw.close();

			// 读取返回内容
			BufferedReader br = new BufferedReader(new InputStreamReader(
					con.getInputStream(), "utf-8"));
			String temp;
			while ((temp = br.readLine()) != null) {
				buffer.append(temp);
				buffer.append("\n");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		} finally {
			if (con != null) {
				con.disconnect();
			}
		}

		return buffer.toString();
	}

}